package com.itheima.d2_algorithm;

/**
 * 目标：演示折半查找（要求：数组是有顺序的，否则是不能做折半查找的）
 */
public class Demo2 {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

        int index = binarySearch(arr, 60);
        System.out.println(index);
    }

    public static int binarySearch(int[] arr, int data) {
        int start = 0;
        int end = arr.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (data == arr[mid]) {
                return mid;
            }

            if (data > arr[mid]) {
                start = mid + 1;
            }

            if (data < arr[mid]) {
                end = mid - 1;
            }
        }
        return -1;
    }
}
